package com.tanhua.server.service;

import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class UserLikeService {
    @DubboReference
    private UserLikeApi userLikeApi;
    @DubboReference
    private FriendApi friendApi;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TanhuaService tanhuaService;

    /**
     * 取消喜欢
     * @param likeUserId
     */
    public void deleteLike(Long likeUserId) {
        //根据用户id和取消喜欢的用户id删除MongoDB中用户
       Boolean delete = userLikeApi.deleteLike(UserHolder.getUserId(),likeUserId);
       if (!delete){
           //失败
           throw new BusinessException(ErrorResult.error());
       }
       //操作redis，删除不喜欢的数据
        redisTemplate.opsForSet().remove(Constants.USER_LIKE_KEY + UserHolder.getUserId(), likeUserId.toString());
       //判断是否双向喜欢
       if (tanhuaService.isLike(UserHolder.getUserId(),likeUserId)){
           //删除好友关系
           friendApi.deleteFriendByFriendId(UserHolder.getUserId(),likeUserId);
       }
    }

    /**
     * 对粉丝进行喜欢
     */
    public void fansLike(Long fansUserId) {
        //判断是否双向喜欢
        if (!tanhuaService.isLike(UserHolder.getUserId(),fansUserId)){
           // 保存MongoDB中UserLike集合用户(有就修改,没有就添加)
            Boolean save = userLikeApi.saveOrUpdateFans(UserHolder.getUserId(),fansUserId);
            if (!save){
                //失败
                throw new BusinessException(ErrorResult.error());
            }
            //操作redis，添加喜欢的数据
            redisTemplate.opsForSet().add(Constants.USER_LIKE_KEY+UserHolder.getUserId(),fansUserId.toString());
            //添加好友关系
            friendApi.save(UserHolder.getUserId(),fansUserId);
        }
    }
}
